package com.aplink.generic.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.aplink.generic.GenericFragment;
import com.aplink.generic.pojo.controlspec.ViewPagerSpec;
import com.aplink.generic.pojo.controlspec.ViewPagerSpec.ViewPagerItem;

public class GenericViewPagerAdapter extends FragmentPagerAdapter {
    private ViewPagerSpec mViewPagerFormat;

    public GenericViewPagerAdapter( FragmentManager fm,
                                    ViewPagerSpec viewPagerFormat ) {
        super( fm );
        mViewPagerFormat = viewPagerFormat;
    }

    @Override
    public Fragment getItem( int arg0 ) {
        try {
            ViewPagerItem pagerItem = mViewPagerFormat.getViewPagerItems().get(
                    arg0 );
            String className = pagerItem.getClassName();
            GenericFragment fragment = (GenericFragment) Class.forName(
                    className ).newInstance();
            return fragment;
        } catch ( InstantiationException e ) {
            e.printStackTrace();
        } catch ( IllegalAccessException e ) {
            e.printStackTrace();
        } catch ( ClassNotFoundException e ) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int getCount() {
        return mViewPagerFormat.getViewPagerItems().size();
    }

    @Override
    public CharSequence getPageTitle( int position ) {
        ViewPagerItem pagerItem = mViewPagerFormat.getViewPagerItems().get(
                position );
        return pagerItem.getTitle();
    }
}
